//
//  MCLotteryHallViewController.m
//  TLYL
//
//  Created by miaocai on 2017/6/1.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCLotteryHallViewController.h"
#import "MCPickNumberViewController.h"
#import "MCUserDefinedLotteryCategoriesViewController.h"
#import "MCHomePageLotteryCategoriesView.h"
#import "MCHomePagePictrueCycleView.h"
#import "MCHomePageInfoCycleView.h"
#import "MCPickNumberViewController.h"
#import "MCLotteryID.h"
#import "MCCZTXView.h"
#import "MCUserDefinedLotteryCategoriesModel.h"
#import "MCWithdrawRecDeltailViewController.h"
#import "MCRechargeViewController.h"
#import "MCUserMoneyModel.h"
#import "MCMineInfoModel.h"
#import "MCHasPayPwdModel.h"
#import "MCDataTool.h"
#import "MCGetLotteryCustomModel.h"
#import "MCSetLotteryCustomModel.h"
#import "MCSystemNoticeDetailViewController.h"
#import "MCSystemNoticeViewController.h"
#import "UIView+MCParentController.h"
#import "MCKefuViewController.h"
#import "MCMineAddBankCardViewController.h"
#import "MCModifyPayPasswordViewController.h"
#import "MCGameRecordViewController.h"
#import "MCFavorableActivityViewController.h"
#import <MJRefresh/MJRefresh.h>
#import "MCGetSecurityStateModel.h"
#import "MCMSecureSettingViewController.h"
#import "MCNewActivityViewController.h"
#import "MCUpdateAppModel.h"
#import "AppDelegate.h"
#import "MCGetRandomSecurityModel.h"
#import "MCRetrievePasswordModel.h"
#import "MCChoiceView.h"
#import "MCThdPartyModel.h"
#import "MCThdPartyView.h"
#import "MCThdLoginModel.h"
#import "MCThdPartyViewController.h"
#import "MCThdPartyGoCZPopView.h"
#import "MCGetThirdPartyBalanceModel.h"
#import "MCGetNickNameModel.h"
#import "MCChangeNickNameModel.h"
#import "MCNewZhuanZhangViewController.h"
#import "MCHongBaoHeader.h"
#import "MCGetMerchantInfoModel.h"
#import "MCKHCenterSucView.h"

@interface MCLotteryHallViewController ()<MCHomePageLotteryCategoriesDelegate,UITableViewDataSource,MCHomePageThdpartyDelegate,UITextFieldDelegate>

typedef void(^MCLotteryHallViewControllerCompeletion)(BOOL result, NSDictionary *data );
//九宫格view
@property(nonatomic,weak)MCHomePageLotteryCategoriesView *lotteryView;
//查询用户余额及冻结金额
@property(nonatomic,strong)MCUserMoneyModel * money_model;
//获取用户详情
@property(nonatomic,strong)MCMineInfoModel *mineInfoModel;
//查询用户是否已设置资金密码
@property(nonatomic,strong)MCHasPayPwdModel *hasPayPwdModel;
//查询是否已设置密保问题
@property(nonatomic,strong)MCGetSecurityStateModel * getSecurityStateModel;
//以tableView 作为base 增加下拉刷新功能
@property(nonatomic,strong)UITableView *baseTabView;

@property (nonatomic,strong)MCUpdateAppModel * updateAppModel;

@property (nonatomic,strong) MCThdPartyModel *thdpartyModel;
//获取所有的密保问题
@property(nonatomic, strong)MCGetRandomSecurityModel * getRandomSecurityModel;
//验证密保答案是否正确
@property(nonatomic, strong)MCRetrievePasswordModel  * retrievePasswordModel;
@property(nonatomic, weak)UIAlertAction *sureAction;
@property(nonatomic, weak)UITextField * textField;
@property (nonatomic,weak)MCThdPartyView *thdPartyView;
@property (nonatomic,strong) MCThdLoginModel *thdLoginModel;
@property (nonatomic,strong) MCGetThirdPartyBalanceModel *getThirdPartyBalanceModel;
@property (nonatomic,strong) MCThdPartyGoCZPopView *coverView;
@property (nonatomic,assign) CGFloat thdPartyMoney;
@property (nonatomic,strong) MCGetNickNameModel *getNickNameModel;
@property (nonatomic,strong) MCChangeNickNameModel *changeNickNameModel;
@property (nonatomic,strong)ApiBaseManager *manager;
@property(nonatomic, strong)UIButton * hongBaoBtn;
@property(nonatomic, strong)MCCheckUserGrabMoneyModel * checkUserGrabMoneyModel;
@property(nonatomic, strong)MCGetMerchantInfoModel *getMerchantInfoModel;

@end


@implementation MCLotteryHallViewController

#pragma mark-life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"正信在线";
    [self setUpUI];
    [self loadData];
    [self addNSNotification];

   
//    float a = [MCMathUnits floatWithdecimalNumber:1.56669999999];
//    NSLog(@"%f",a);
//    //比对版本号  看是否需要强制更新
//    [self checkUpdateApp];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = MC_THEME_COLOR;
    self.navigationController.navigationBarHidden=NO;
    self.navigationController.navigationBar.translucent = NO;
    NSString  *Token= [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    if (Token.length>1) {
        [self reloadData];
    }
    
     [self loadThdPartyData];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"MCHomePageInfoCycleViewNotification" object:nil];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"MCHomePageInfoCycleViewNotification" object:nil];
}
-(void)addNSNotification{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadDefaultCZList) name:HomePageDidLoadDefaultCatergeryListNSNotification object:nil];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    //比对版本号  看是否需要强制更新
    [self checkUpdateApp];
}
//检测更新
-(void)checkUpdateApp{
    __weak __typeof(self)wself = self;
    MCUpdateAppModel * updateAppModel = [MCUpdateAppModel sharedMCUpdateAppModel];
    updateAppModel.DownloadUrl=@"";
    _updateAppModel=updateAppModel;
    
    [updateAppModel refreashDataAndShow];
    
    updateAppModel.callBackSuccessBlock = ^(id manager) {
       
        NSDictionary * dic = manager;
        if (dic[@"DownloadUrl"]) {
            NSString * url = [NSString stringWithFormat:@"%@",dic[@"DownloadUrl"]];
            wself.updateAppModel.DownloadUrl=url;
            if (url.length>0) {
                //有更新
                [wself openUpdate:url];
            }
        }
        
    };
    
    updateAppModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
        
    };
    
}
-(void)openUpdate:(NSString *)url{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"发现新版本，请更新！" preferredStyle:UIAlertControllerStyleAlert];
    // 添加按钮
    //    __weak __typeof__ (self) wself = self;
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
        
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        UIWindow *window = app.window;
        
        [UIView animateWithDuration:0.4f animations:^{
            window.alpha = 0;
            window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
        } completion:^(BOOL finished) {
            exit(0);
        }];
        
    }]];

    
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
        AppDelegate *app = (AppDelegate *)[UIApplication sharedApplication].delegate;
        UIWindow *window = app.window;
        
        [UIView animateWithDuration:0.4f animations:^{
            window.alpha = 0;
            window.frame = CGRectMake(0, window.bounds.size.width, 0, 0);
        } completion:^(BOOL finished) {
            exit(0);
        }];
        
        
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark-setUpUI
- (void)setUpUI{
    self.automaticallyAdjustsScrollViewInsets = NO;
    UITableView *tab = [[UITableView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:tab];
    self.baseTabView = tab;
    tab.dataSource= self;
    tab.rowHeight = G_SCREENHEIGHT - kStatusBarAndNavigationBarHeight;
    tab.contentInset = UIEdgeInsetsMake(0, 0, MC_REALVALUE(184), 0);
    tab.backgroundColor = RGB(239, 239, 239);
    __weak typeof(self) weakSelf = self;
    [self.baseTabView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"1"];
    self.baseTabView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf loadDefaultCZList];
    }];
    CGFloat naviHeight = 0;
    //轮播高度
    CGFloat picCycleHeight = MC_REALVALUE(110);
    //3S广告
    CGFloat PageInfoCycleHeight = MC_REALVALUE(30);
    //充值提现
    CGFloat cztxViewHeight = MC_REALVALUE(100);
    //选择按钮
    CGFloat choiceViewHeight = MC_REALVALUE(30);
    
    MCChoiceView *choiceView = [[MCChoiceView alloc] initWithFrame:CGRectMake(0, picCycleHeight + naviHeight + cztxViewHeight + PageInfoCycleHeight, G_SCREENWIDTH, MC_REALVALUE(30))];
    [tab addSubview:choiceView];
    
    /*
     * 九宫格  彩种
     */
    MCHomePageLotteryCategoriesView *lotteryView = [[MCHomePageLotteryCategoriesView alloc] initWithFrame:CGRectMake(0, naviHeight + picCycleHeight + PageInfoCycleHeight + cztxViewHeight +0.5 + choiceViewHeight, G_SCREENWIDTH, G_SCREENHEIGHT -(naviHeight + picCycleHeight + PageInfoCycleHeight + cztxViewHeight) - 20 - choiceViewHeight+100)];
    [tab addSubview:lotteryView];
    lotteryView.delegate=self;
    lotteryView.hidden = NO;
    _lotteryView=lotteryView;
    lotteryView.collectionViewDidSelectedCallBack = ^(MCUserDefinedLotteryCategoriesModel *model){
        // 彩种开售 SaleState == 1
   
        if ([model.SaleState intValue]==1) {
            MCPickNumberViewController *pickVC =  [[MCPickNumberViewController alloc] init];
            pickVC.lotteriesTypeModel = model;
            [weakSelf.navigationController pushViewController:pickVC animated:YES];
        }else{
            [SVProgressHUD showInfoWithStatus:@"该彩种已停售！"];
            return ;
        }
        
    };
    /*
     * 九宫格  3方
     */
    
    MCThdPartyView *thdView = [[MCThdPartyView alloc] initWithFrame:CGRectMake(0, naviHeight + picCycleHeight + PageInfoCycleHeight + cztxViewHeight +0.5 + choiceViewHeight, G_SCREENWIDTH, G_SCREENHEIGHT -(naviHeight + picCycleHeight + PageInfoCycleHeight + cztxViewHeight) - 49 - choiceViewHeight)];
    [tab addSubview:thdView];
    thdView.delegate=self;
    thdView.collectionViewDidSelectedCallBack = ^(MCThdPartyModel *model){
        
       
        if ([model.ThirdpartyValue intValue] == 1 ||[model.ThirdpartyValue intValue] == 2) {
            [weakSelf loadThdYuEDataWithModel:model];
            [weakSelf alertViewGoToChongZhiWithMCThdPartyModel:model];
            
        } else {
            
         [weakSelf getNickNameDataWithModel:model];
            
        }

    };
    self.thdPartyView = thdView;
    thdView.hidden = YES;
    lotteryView.hidden =NO;
    choiceView.lotteryBlock = ^{
        thdView.hidden = YES;
        lotteryView.hidden =NO;
    };
    choiceView.qiPaiBlock = ^{
        thdView.hidden = NO;
        lotteryView.hidden =YES;
        if (self.thdPartyView.dataMarry.count == 0) {
           [self performSelector:@selector(toast) withObject:nil afterDelay:0.1];
        }
        
    };
    

    /*
     * 轮播
     */
    MCHomePagePictrueCycleView *picView = [[MCHomePagePictrueCycleView alloc] initWithFrame:CGRectMake(0, naviHeight, G_SCREENWIDTH, picCycleHeight)];
    [tab addSubview:picView];
    /*
     * 3S广告通知栏
     */
    MCHomePageInfoCycleView *infoView = [[MCHomePageInfoCycleView alloc] initWithFrame:CGRectMake(0, picCycleHeight + naviHeight + MC_REALVALUE(100), G_SCREENWIDTH, PageInfoCycleHeight)];
    [tab addSubview:infoView];
    infoView.systemNoticeClickBlock = ^(MCSystemNoticeListModel *model) {
//        self.tabBarController.selectedIndex = 2;
        
        [UIView animateWithDuration:0.001 animations:^{
            MCSystemNoticeViewController * vc=[[MCSystemNoticeViewController alloc]init];
            vc.isNeedPush=YES;
            vc.NewsID=model.MerchantNews_ID;
            [self.navigationController pushViewController:vc animated:NO];
        } completion:^(BOOL finished) {

            
            
        }];

        
    };
    
    /*
     * 充值 提现 栏
     */
    MCCZTXView *cztxView = [[MCCZTXView alloc] initWithFrame:CGRectMake(0, picCycleHeight + naviHeight, G_SCREENWIDTH, cztxViewHeight)];
    
    cztxView.tixianBtnClickBlock = ^{
        
        if ([self.mineInfoModel.UserType intValue] ==1) {
            [SVProgressHUD showInfoWithStatus:@"您无提款权限！"];
            return;
        }
        BOOL hasCard = [self.mineInfoModel.BankCardNumber length]>1?YES:NO;
        BOOL hasPassword = [self.hasPayPwdModel.PayOutPassWord intValue]==1?YES:NO;
        /*
         * 情况一： 无资金密码  无默认银行卡
         */
        if (!hasCard&&!hasPassword) {
            [SVProgressHUD showInfoWithStatus:@"请先完善银行卡！"];
            
            [self performSelector:@selector(delay_GoToMCMineAddBankCardViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];

            
            //情况二： 有资金密码  无默认银行卡
        }else if (hasPassword&&!hasCard){
            
            [SVProgressHUD showInfoWithStatus:@"请先完善银行卡！"];
            
            [self performSelector:@selector(delay_GoToMCMineAddBankCardViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];

            
            //情况三： 无资金密码  有默认银行卡
        }else if (!hasPassword&&hasCard){
            
            //设置资金密码-》退回我的
//            [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
            
            MCGetSecurityStateModel * getSecurityStateModel = [MCGetSecurityStateModel sharedMCGetSecurityStateModel];
            if (getSecurityStateModel.hadSecurityState.length>0) {
                if ([getSecurityStateModel.hadSecurityState integerValue]==1) {
                    //设置资金密码-》退回我的
                    [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
                    [self performSelector:@selector(delay_GoToMCModifyPayPasswordViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                    
                    
                }else{
                    //设置密保
                    [SVProgressHUD showInfoWithStatus:@"请先设置密保！"];
                    
                    
                    [self performSelector:@selector(delay_GoToMCMSecureSettingViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                    
                }
            }else{
                __weak __typeof(self)wself = self;
                [self GetSecurityState:^(BOOL result, NSDictionary *data) {
                    if (result) {
                        wself.getSecurityStateModel.hadSecurityState=[NSString stringWithFormat:@"%@",data[@"Result"]];
                        if ([wself.getSecurityStateModel.hadSecurityState integerValue]==1) {
                            //设置资金密码-》退回我的
                            [SVProgressHUD showInfoWithStatus:@"请先设置资金密码！"];
                            
                            [self performSelector:@selector(delay_GoToMCModifyPayPasswordViewController) withObject:nil/*可传任意类型参数*/ afterDelay:1.0];
                            
                        }else{
                            [SVProgressHUD showInfoWithStatus:@"加载失败！"];
                        }
                    }
                }];
            }
            
            
            //情况四： 有资金密码  有默认银行卡
        }else{
            
            MCWithdrawRecDeltailViewController * vc=[[MCWithdrawRecDeltailViewController alloc]init];
            self.navigationController.navigationBarHidden=NO;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
    };
    
    cztxView.chongzhiBtnClickBlock = ^{
        if ([self.mineInfoModel.UserType intValue] ==1) {
            [SVProgressHUD showInfoWithStatus:@"您无充值权限！"];
            return;
        }
        MCRechargeViewController * vc = [[MCRechargeViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    };
    cztxView.gameBtnClickBlock = ^{
        MCGameRecordViewController * vc=[[MCGameRecordViewController alloc]init];
    
        [self.navigationController pushViewController:vc animated:YES];
    };
    cztxView.activityBtnClickBlock = ^{
        MCNewActivityViewController * vc=[[MCNewActivityViewController alloc]init];

        [self.navigationController pushViewController:vc animated:YES];
    };
    [tab addSubview:cztxView];
    
    
    /*
     * 客服按钮
     */
    UIButton *btn = [[UIButton alloc] init];
    [btn setBackgroundImage:[UIImage imageNamed:@"icon_customer_service"] forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, 0, 25, 25);
    btn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    [btn addTarget:self action:@selector(contactCustomerServiceBtnClick:) forControlEvents:UIControlEventTouchDown];
    UIView *v = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    [v addSubview:btn];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:v];
    self.navigationItem.rightBarButtonItem = rightItem;
    /*
     * Copyright
     */
    
    UILabel *label = [[UILabel alloc] init];
    label.text = @"正信在线© 2018 Copyright";
    label.textAlignment=NSTextAlignmentCenter;
    label.textColor =RGB(136,136,136);
    label.font = [UIFont systemFontOfSize:9.0];
    [tab addSubview:label];
    
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.lotteryView.mas_bottom).offset(10);
    }];
    
    
    _hongBaoBtn = [[UIButton alloc] initWithFrame:CGRectMake(G_SCREENWIDTH-W_hongBao-5, G_SCREENHEIGHT-kTabBarHeight-kStatusBarAndNavigationBarHeight-8-H_hongBao, W_hongBao,H_hongBao)];
    _hongBaoBtn.backgroundColor=[UIColor clearColor];
    _hongBaoBtn.layer.masksToBounds = YES;
    [_hongBaoBtn addTarget:self action:@selector(openHongBao) forControlEvents:UIControlEventTouchUpInside];
    [_hongBaoBtn setBackgroundImage:[UIImage imageNamed:@"hbann"] forState:UIControlStateNormal];
    [self.view addSubview:_hongBaoBtn];
    [_hongBaoBtn setTitleColor:RGB(255, 69, 69) forState:UIControlStateNormal];
    [_hongBaoBtn setTitle:@"" forState:UIControlStateNormal];
    _hongBaoBtn.titleLabel.font = [UIFont systemFontOfSize: 10.0];
    _hongBaoBtn.contentEdgeInsets = UIEdgeInsetsMake(20,0, 0, 0);
}

#pragma mark-打开红包
-(void)openHongBao{
    
    MCHongBaoDataModel * dataSource = [MCHongBaoDataModel sharedMCHongBaoDataModel];
    
    if (dataSource.hongBaoMarray.count<1) {
        [SVProgressHUD showInfoWithStatus:@"暂无红包！"];
        return;
    }
    
    __weak __typeof(self)wself = self;
    MCOpenHongBaoViewController *VC = [[MCOpenHongBaoViewController alloc]init];
    VC.goToDetailBlock = ^{
        MCHongBaoRecordViewController * detatilVC=[[MCHongBaoRecordViewController alloc]init];
        [wself.navigationController pushViewController:detatilVC animated:YES];
    };
    VC.relayOutHongBaoDataBlock = ^{
        MCHongBaoDataModel * dataSource = [MCHongBaoDataModel sharedMCHongBaoDataModel];
        NSString * num = [NSString stringWithFormat:@"%ld",dataSource.hongBaoMarray.count];
        [wself relayoutHongBao:num];
    };
    VC.dismissHongBaoVCBlock = ^{
        MCHongBaoDataModel * dataSource = [MCHongBaoDataModel sharedMCHongBaoDataModel];
        NSString * num = [NSString stringWithFormat:@"%ld",dataSource.hongBaoMarray.count];
        [wself relayoutHongBao:num];
    };
    MCHongBaoPresentationController *PC = [[MCHongBaoPresentationController alloc] initWithPresentedViewController:VC presentingViewController:self];
    VC.transitioningDelegate = PC;
    [self presentViewController:VC animated:YES completion:NULL];
    
}

-(void)relayoutHongBao:(NSString *)num{

    [self.hongBaoBtn setTitle:num forState:UIControlStateNormal];
    if ([num isEqualToString:@"0"]||(![MCHongBaoDataModel isOpen_All_HB])) {
        self.hongBaoBtn.hidden = YES;
    }else{
        self.hongBaoBtn.hidden = NO;
    }
}


- (void)getNickNameDataWithModel:(MCThdPartyModel *)model{
    __weak typeof(self) wself = self;
    
    MCGetNickNameModel * getThirdPartyBalanceModel = [[MCGetNickNameModel alloc]init];
    self.getNickNameModel = getThirdPartyBalanceModel;
    [getThirdPartyBalanceModel refreashDataAndShow];
    [SVProgressHUD show];
    getThirdPartyBalanceModel.callBackSuccessBlock = ^(id manager) {
        [SVProgressHUD dismiss];
//manager[@"NickName"]
        BOOL hasChinese = [self hasChinese:manager[@"NickName"]];
        if (hasChinese || [manager[@"NickName"] isEqualToString:@""]) {
            [wself alertViewChangeNameWithMCThdPartyModel:model];
        } else {
             [wself loadThdYuEDataWithModel:model];
            [wself alertViewGoToChongZhiWithMCThdPartyModel:model];
        }
    };
    
    getThirdPartyBalanceModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
        [SVProgressHUD dismiss];
    };

}

- (void)changeNickNameRequst:(NSString *)str andModel:(MCThdPartyModel *)model{
    __weak typeof(self) wself = self;
    
    MCChangeNickNameModel * getThirdPartyBalanceModel = [[MCChangeNickNameModel alloc]init];
    getThirdPartyBalanceModel.NickName = str;
    self.changeNickNameModel = getThirdPartyBalanceModel;
    [getThirdPartyBalanceModel refreashDataAndShow];
    [SVProgressHUD show];
    getThirdPartyBalanceModel.callBackSuccessBlock = ^(id manager) {
        [SVProgressHUD dismiss];
        [wself loadThdYuEDataWithModel:model];
        [wself alertViewGoToChongZhiWithMCThdPartyModel:model];
    };
    
    getThirdPartyBalanceModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        
        [SVProgressHUD showInfoWithStatus:manager.responseMessage];
    };

}
- (void)alertViewGoToChongZhiWithMCThdPartyModel:(MCThdPartyModel *)model{
    
    MCThdPartyGoCZPopView *coverView = [[MCThdPartyGoCZPopView alloc]initWithTitle:@"提示" confirm:@"进入游戏" cancel:@"关闭"];
    [self.navigationController.view addSubview:coverView];
    self.coverView = coverView;
    [coverView show];
     self.coverView.dingDanLabel.text = [NSString stringWithFormat:@"%@账户余额：%@元",model.ThirdpartyText, @"--"];
    __weak typeof(self) weakSelf = self;

    coverView.gotoChongzhiBlock = ^{
        [SVProgressHUD dismiss];

        MCNewZhuanZhangViewController *vc = [[MCNewZhuanZhangViewController alloc] init];
//        if ([weakSelf.mineInfoModel.UserType intValue] ==1) {
//            [SVProgressHUD showInfoWithStatus:@"您无充值权限！"];
//            return;
//        }
//        MCRechargeViewController * vc = [[MCRechargeViewController alloc]init];
        [weakSelf.navigationController pushViewController:vc animated:YES];
    };
    
    coverView.continueBtnBlock = ^{
        [SVProgressHUD dismiss];
        [weakSelf loadThdLoginDataId:model.ThirdpartyValue andName:[[NSUserDefaults standardUserDefaults]objectForKey:@"UserName"] andNaviName:model.ThirdpartyText];
//        if (weakSelf.thdPartyMoney == 0) {
//            
//        } else {
//          [weakSelf loadThdLoginDataId:model.ThirdpartyValue andName:[[NSUserDefaults standardUserDefaults]objectForKey:@"UserName"] andNaviName:model.ThirdpartyText];
//        }

    };
    coverView.cancelBtnBlock = ^{
      [SVProgressHUD dismiss];
    };
 
}

- (void)alertViewChangeNameWithMCThdPartyModel:(MCThdPartyModel*)model{
    __weak typeof(self) weakSelf = self;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"幸运昵称" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    //以下方法就可以实现在提示框中输入文本；
    
    //在AlertView中添加一个输入框
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        
        textField.placeholder = @"由4-25个数字、字母组成";
    }];
    
    //添加一个确定按钮 并获取AlertView中的第一个输入框 将其文本赋值给BUTTON的title
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        UITextField *envirnmentNameTextField = alertController.textFields.firstObject;
        
      
       BOOL hasChinese = [self judgeNickNameLegal:envirnmentNameTextField.text];
        if (hasChinese == NO) {
            [SVProgressHUD showInfoWithStatus:@"昵称不符合规则"];
            return ;
        } else {
            
            
            [weakSelf changeNickNameRequst:envirnmentNameTextField.text andModel:model];
            
          
        }

        
    }]];
    
    //添加一个取消按钮
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    
    //present出AlertView
    [self presentViewController:alertController animated:true completion:nil];
}
- (BOOL)judgeNickNameLegal:(NSString *)pass{
    BOOL result = false;
//    /^(?!\\d+$)[\\da-zA-Z]{4,25}$/
    NSString * regex = @"^(?![0-9]+$)[0-9A-Za-z]{4,25}$";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    result = [pred evaluateWithObject:pass];
    return result;
}
- (BOOL)hasChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}

#pragma mark ---tableView delegate and datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

//默认彩种
-(void)loadDefaultCZList{
    
    __weak typeof(self) weakSelf = self;
    MCUserDefinedLotteryCategoriesViewController * vc=[[MCUserDefinedLotteryCategoriesViewController alloc]init];
    [vc GetLotteryCustomArray:^(BOOL result, NSMutableArray *defaultCZArray) {
        [weakSelf.baseTabView.mj_header endRefreshing];
        if (result) {
            [weakSelf.lotteryView relayOutUI];
        }
    }];
}


- (void)loadData{
    [self loadDefaultCZList];
    [self GetSecurityState:^(BOOL result, NSDictionary *data) {
        
    }];


 
}


// 第三方余额接口
- (void)loadThdYuEDataWithModel:(MCThdPartyModel *)model{
    __weak typeof(self) wself = self;
    NSDictionary * dic =@{
                          @"ID":model.ThirdpartyValue,
                          @"UserName":[[NSUserDefaults standardUserDefaults] objectForKey:@"UserName"]
                          };
    
    MCGetThirdPartyBalanceModel * getThirdPartyBalanceModel = [[MCGetThirdPartyBalanceModel alloc]initWithDic:dic];
    self.getThirdPartyBalanceModel = getThirdPartyBalanceModel;
    [getThirdPartyBalanceModel refreashDataAndShow];
    [SVProgressHUD show];
    getThirdPartyBalanceModel.callBackSuccessBlock = ^(id manager) {
        [SVProgressHUD dismiss];
        
        
        
        __block NSString * Balance = [NSString stringWithFormat:@"%@",manager[@"Balance"]];
        
        if ([Balance containsString:@"null"]||[Balance integerValue]<0||Balance.length<1) {
            
            
            MCThdLoginModel * thdModel=[[MCThdLoginModel alloc] init];
            thdModel.ID = dic[@"ID"];
            thdModel.UserName = dic[@"UserName"];;
            [thdModel refreashDataAndShow];
            self.thdLoginModel=thdModel;
            thdModel.callBackSuccessBlock = ^(NSDictionary *manager) {
                [BKIndicationView dismiss];
                if ( [manager.allKeys containsObject:@"LoginUrl"] && [manager[@"LoginUrl"] isEqualToString:@""] == NO) {
                    
                    Balance = @"0";
                    
                }else{
                    Balance = @"--";
//                    [SVProgressHUD showInfoWithStatus:@"查询失败！"];
                }
                
                Balance=GetRealSNum(Balance);
                wself.coverView.dingDanLabel.text = [NSString stringWithFormat:@"%@账户余额：%@元",model.ThirdpartyText, Balance];
                wself.thdPartyMoney = [Balance floatValue];
                
            };
            thdModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
                
                [BKIndicationView dismiss];
            };
            
        }
        

        if (manager[@"Balance"] == nil) {
              wself.coverView.dingDanLabel.text = [NSString stringWithFormat:@"%@账户余额：%@元",model.ThirdpartyText,@0];
            wself.thdPartyMoney = 0;
            return ;
        }
        wself.coverView.dingDanLabel.text = [NSString stringWithFormat:@"%@账户余额：%@元",model.ThirdpartyText, Balance];
        wself.thdPartyMoney = [Balance floatValue];

    };
    
    getThirdPartyBalanceModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
          [SVProgressHUD dismiss];
    };
}
// 第三方平台接口
- (void)loadThdPartyData{
    __weak typeof(self)wself = self;
   
    MCThdPartyModel * thdModel=[[MCThdPartyModel alloc] init];
    [thdModel refreashDataAndShow];
    self.thdpartyModel=thdModel;
    thdModel.callBackSuccessBlock = ^(id manager) {
        
        NSArray *temp= [MCThdPartyModel mj_objectArrayWithKeyValuesArray:manager[@"TransferDirection"]];
     
            
        NSMutableArray * arr = [NSMutableArray array];
        for (MCThdPartyModel *m in temp) {
            if ([m.IsShow intValue] == 1) {
                [arr addObject:m];
               
            }
        }
        wself.thdPartyView.dataMarry = [arr copy];
        NSArray *m = [MCThdPartyModel mj_keyValuesArrayWithObjectArray:[arr copy]];
        [[NSUserDefaults standardUserDefaults] setObject:m forKey:@"thdPartyViewdataMarry"];

    };
    
    thdModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {


        wself.manager = manager;
        if ([manager.responseMessage containsString:@"测试账号无法进入第三方游戏平台"]) {
            
        }else{
            [self performSelector:@selector(showInfo) withObject:nil afterDelay:2];
           

        }
    };
 
}
- (void)showInfo{
    if (self.manager.responseMessage) {
        [SVProgressHUD showInfoWithStatus:self.manager.responseMessage];
    }
    
}
- (void)toast{
    [SVProgressHUD showInfoWithStatus:@"棋牌专区暂未开启!"];
}
//第三方登录接口
- (void)loadThdLoginDataId:(NSNumber *)ID andName:(NSString *)name andNaviName:(NSString *)title{
    

    __weak typeof(self)wself = self;
    
    MCThdLoginModel * thdModel=[[MCThdLoginModel alloc] init];
    thdModel.ID = ID;
    thdModel.UserName = name;
    [thdModel refreashDataAndShow];
    self.thdLoginModel=thdModel;
    thdModel.callBackSuccessBlock = ^(NSDictionary *manager) {
        
        if ( [manager.allKeys containsObject:@"LoginUrl"] && [manager[@"LoginUrl"] isEqualToString:@""] == NO) {
            MCThdPartyViewController *vc = [[MCThdPartyViewController alloc] init];
            vc.url = manager[@"LoginUrl"];
            vc.mytitle = title;
            [wself.navigationController pushViewController:vc animated:YES];
        }else{
            [SVProgressHUD showInfoWithStatus:@"链接地址无效！"];
        }
       
    };
    
    thdModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
     wself.manager = manager;
        if ([manager.responseMessage containsString:@"测试账号无法进入第三方游戏平台"]) {
            
        }else{
            [self performSelector:@selector(showInfo) withObject:nil afterDelay:2];
            
        }
    };
}
- (void)reloadData{

    __weak typeof(self)wself = self;
//  查询用户余额及冻结金额
    MCUserMoneyModel * money_model=[MCUserMoneyModel sharedMCUserMoneyModel];
    [money_model refreashDataAndShow];
    self.money_model=money_model;
    money_model.callBackSuccessBlock = ^(id manager) {
  
        wself.money_model.FreezeMoney = manager[@"FreezeMoney"];
        wself.money_model.LotteryMoney = manager[@"LotteryMoney"];
    };
    
    //  获取用户详情
    MCMineInfoModel *mineInfo_model = [MCMineInfoModel sharedMCMineInfoModel];
    self.mineInfoModel = mineInfo_model;
    [mineInfo_model refreashDataAndShow];
    mineInfo_model.callBackSuccessBlock = ^(id manager) {
      
        wself.mineInfoModel=[MCMineInfoModel mj_objectWithKeyValues:manager];
        
    };
    //查询用户是否已设置资金密码
    MCHasPayPwdModel * hasPayPwd_model=[MCHasPayPwdModel sharedMCHasPayPwdModel];
    [hasPayPwd_model refreashDataAndShow];
    self.hasPayPwdModel=hasPayPwd_model;
    hasPayPwd_model.callBackSuccessBlock = ^(id manager) {
       
        wself.hasPayPwdModel.PayOutPassWord=[NSString stringWithFormat:@"%@",manager[@"PayOutPassWord"]];
    };
    
    MCGetMerchantInfoModel *getMerchantInfoModel = [MCGetMerchantInfoModel sharedMCGetMerchantInfoModel];
    
    [getMerchantInfoModel refreashDataAndShow];
    self.getMerchantInfoModel = getMerchantInfoModel;
    getMerchantInfoModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
    };
    getMerchantInfoModel.callBackSuccessBlock = ^(id manager) {
    };
    
    MCHongBaoDataModel * dataSource = [MCHongBaoDataModel sharedMCHongBaoDataModel];
    NSString * num = [NSString stringWithFormat:@"%ld",dataSource.hongBaoMarray.count];
    [wself.hongBaoBtn setTitle:num forState:UIControlStateNormal];
    [self relayoutHongBao:num];
//    if ([MCHongBaoDataModel isOpen_All_HB]) {
//        _hongBaoBtn.hidden=NO;
//    }else{
//        _hongBaoBtn.hidden=YES;
//    }
    if ([dataSource isShouldRefreashHongBaoData]) {
        [self relayOutHongBaoData:^(BOOL result, NSMutableArray *HongBaoArray) {
            if (result) {
                MCHongBaoDataModel * dataSource = [MCHongBaoDataModel sharedMCHongBaoDataModel];
                NSString * num = [NSString stringWithFormat:@"%ld",dataSource.hongBaoMarray.count];
                [self relayoutHongBao:num];
            }
        }];
    }
    
}
//查询密保设置状态
-(void)GetSecurityState:(MCLotteryHallViewControllerCompeletion)Compeletion{
    __weak typeof(self)wself = self;
    MCGetSecurityStateModel * getSecurityStateModel = [MCGetSecurityStateModel sharedMCGetSecurityStateModel];
    _getSecurityStateModel=getSecurityStateModel;
    [getSecurityStateModel refreashDataAndShow];
    getSecurityStateModel.callBackSuccessBlock = ^(id manager) {
        wself.getSecurityStateModel.hadSecurityState=[NSString stringWithFormat:@"%@",manager[@"Result"]];
        Compeletion(YES,manager);
    };
    getSecurityStateModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
        wself.getSecurityStateModel.hadSecurityState=nil;
        Compeletion(NO,nil);
    };
}

#pragma mark-touch event
- (void)contactCustomerServiceBtnClick:(UIButton *)btn{
    MCKefuViewController *vc =  [[MCKefuViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];

}
/*
 * 跳转自定义彩种
 */
#pragma mark-MCHomePageLotteryCategoriesDelegate
-(void)SetUserDefinedLotteryCategories{
    MCUserDefinedLotteryCategoriesViewController * vc = [[MCUserDefinedLotteryCategoriesViewController alloc]init];
    __weak typeof(self) weakSelf = self;
    vc.block=^(NSMutableArray<MCUserDefinedLotteryCategoriesModel *> *marr){
        
        [weakSelf.lotteryView relayOutUI];
        
    };
    
    [self.navigationController pushViewController:vc animated:YES];

}


#pragma mark-添加银行卡
-(void)delay_GoToMCMineAddBankCardViewController{
    //先绑卡-》设置资金密码-》退回我的
    MCMineAddBankCardViewController * vc=[[MCMineAddBankCardViewController alloc]init];
    vc.type=NOPasswordAndNOCard;
    self.navigationController.navigationBarHidden=NO;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark-资金密码
-(void)delay_GoToMCModifyPayPasswordViewController{
    //先验证密保问题
    [self enSureSecureQuestion];

}

#pragma mark-验证密保
-(void)enSureSecureQuestion{
    __weak __typeof__ (self) wself = self;
    
    MCGetRandomSecurityModel * getRandomSecurityModel = [MCGetRandomSecurityModel sharedMCGetRandomSecurityModel];

    _getRandomSecurityModel=getRandomSecurityModel;
    [BKIndicationView showInView:self.view];
    [getRandomSecurityModel refreashDataAndShow];
    getRandomSecurityModel.callBackSuccessBlock = ^(id manager) {
        NSArray * arr =manager;
        if (arr.count>0) {
            wself.getRandomSecurityModel.dataSource = [MCSecurityQuestionModel mj_objectWithKeyValues:manager[0]];
            [wself popRandomSecurity:wself.getRandomSecurityModel.dataSource];
        }
        
    };
    
    getRandomSecurityModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
    };

}

-(void)popRandomSecurity:(MCSecurityQuestionModel *)model{
    __weak __typeof__ (self) wself = self;
    
    NSString * question = [NSString stringWithFormat:@"\n%@",model.Question];
    //创建UIAlertController 设置标题，信息，样式
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"验证密保问题" message:question preferredStyle:UIAlertControllerStyleAlert];
    
    //添加UITextField
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"请输入答案！";
        textField.keyboardType = UIKeyboardTypeDefault;
        [textField addTarget:wself action:@selector(textFieldChane:) forControlEvents:UIControlEventEditingChanged];
        _textField=textField;
    }];
    
    //创建UIAlertAction对象，设置标题并添加到UIAlertController上
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDestructive handler:nil];
    [alertController addAction:cancelAction];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [self retrievePasswordModel:model];
        
    }];
    sureAction.enabled=NO;
    _sureAction=sureAction;
    //设置UIAlertAction对象是否可用
    [alertController addAction:sureAction];
    
    //展现UIAlertController
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark-验证密保答案是否正确
-(void)retrievePasswordModel:(MCSecurityQuestionModel *)model{
    
    __weak __typeof__ (self) wself = self;
    MCMineInfoModel * mineInfoModel=[MCMineInfoModel sharedMCMineInfoModel];
    
    NSString * UserName;
    if (mineInfoModel.UserName.length>1) {
        UserName=mineInfoModel.UserName;
    }else{
        UserName=[[NSUserDefaults standardUserDefaults] objectForKey:@"UserName"];
    }
    NSDictionary * dic = @{
                           @"UserName":UserName,//    是    String    用户名称
                           @"RecoveryMode":@"2",//    是    Int    找回方式（1：按资金密码 2：通过密保答案找回），此处传固定值2
                           @"SecurityID":model.ID,//    是    Int    当前问题的ID值
                           @"Answer":_textField.text//    是    String    用户输入答案
                           };
    MCRetrievePasswordModel * retrievePasswordModel = [[MCRetrievePasswordModel alloc]initWithDic:dic];
    _retrievePasswordModel = retrievePasswordModel;
    [BKIndicationView showInView:self.view];
    [retrievePasswordModel refreashDataAndShow];
    retrievePasswordModel.callBackSuccessBlock = ^(id manager) {
        
        MCModifyPayPasswordViewController * vc =[[MCModifyPayPasswordViewController alloc]init];
        wself.navigationController.navigationBarHidden=NO;
        [wself.navigationController pushViewController:vc animated:YES];
        
    };
    
    retrievePasswordModel.callBackFailedBlock = ^(id manager, NSString *errorCode) {
    };
    
    
    
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    return NO;
}
-(void)textFieldChane:(UITextField *)tf{
    if (tf.text.length>0) {
        _sureAction.enabled=YES;
    }else{
        _sureAction.enabled=NO;
    }
}


#pragma mark-密保设置
-(void)delay_GoToMCMSecureSettingViewController{
    MCMSecureSettingViewController *svc=[[MCMSecureSettingViewController alloc]init];
    svc.Type = MCMSecureSettingType_FirstSet;
    self.navigationController.navigationBarHidden=NO;
    [self.navigationController pushViewController:svc animated:YES];
}
-(void)relayOutHongBaoData:(OpenHongBaoCompeletion)Compeletion{
    
    NSDictionary * dic=@{};
    
    MCCheckUserGrabMoneyModel * checkUserGrabMoneyModel = [[MCCheckUserGrabMoneyModel alloc]initWithDic:dic];
    [checkUserGrabMoneyModel refreashDataAndShow];
    self.checkUserGrabMoneyModel = checkUserGrabMoneyModel;
    
    checkUserGrabMoneyModel.callBackFailedBlock = ^(ApiBaseManager *manager, NSString *errorCode) {
        Compeletion(NO,nil);
    };
    
    checkUserGrabMoneyModel.callBackSuccessBlock = ^(id manager) {
        NSArray * arr = manager;

        MCHongBaoDataModel * dataSource = [MCHongBaoDataModel sharedMCHongBaoDataModel];
        [dataSource setDataWithArr:arr];
        Compeletion(YES,dataSource.hongBaoMarray);

    };
}

@end




